package com.zzyl.framework.interceptor.impl;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class MemberInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
      //从请求头中获取token
        String token = request.getHeader("authorization");
       //判断token是否存在，不在反401
        if(ObjectUtil.isEmpty(token)){
            extracted(response);
        }

        //解析token，不对401
        Claims claims = null;
        try {
            claims = tokenService.parseToken(token);
        } catch (Exception e) {
            extracted(response);
        }
        //从token中获取userid，得不到401
        Long userId = MapUtil.getLong(claims, "userId");
        if(ObjectUtil.isNull(userId)){
            extracted(response);
        }

         //取到存入
        UserThreadLocal.set(userId);

        //放行
        return true;
    }

    private static void extracted(HttpServletResponse response) {
        response.setStatus(401);
        throw  new BaseException("错误");
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
      UserThreadLocal.remove();
    }
}
